//
//  SecondSearchController.m
//  quickLook
//
//  Created by J on 15/8/31.
//  Copyright (c) 2015年 JZJ. All rights reserved.
//

#import "SecondSearchController.h"

#import "NSString+URLEncode.h"

#import "DownLoad.h"


#import "Header.h"

#import "ThridSearchController.h"


#import "Model.h"
#import "NavisearchCell.h"

#import "ThirdNaviSearchController.h"
#define KEY @"HISTORYARRAY"



@interface SecondSearchController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
{

    BOOL isEmpty;

}

@property(nonatomic,strong)UITableView* tableView;

@property (nonatomic,copy) NSArray *dataArray;


@property (nonatomic,strong) NSMutableArray *searchArray;


@property(nonatomic,strong)UISearchBar* searchBar;


@end

@implementation SecondSearchController

- (void)viewDidLoad {
    [super viewDidLoad];


    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [_tableView setTableFooterView:view];
    
    [_tableView setTableHeaderView:view];
    
    
    
    
    
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(pop)];
    
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    
    //加上 搜索栏
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 35)];//allocate titleView
    
//    UIColor *color =  self.navigationController.navigationBar.barTintColor;
    
//    [titleView setBackgroundColor:color];
    
    _searchBar = [[UISearchBar alloc] init];
    
    _searchBar.delegate = self;
    _searchBar.frame = CGRectMake(0, 0, 200, 30);
//    _searchBar.backgroundColor = color;
//    _searchBar.layer.cornerRadius = 25;
    _searchBar.layer.masksToBounds = YES;
    [_searchBar.layer setBorderWidth:0];
    [_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];  //设置边框为白色
    
    _searchBar.placeholder = @"|搜索作品名、 作者名";
//    [titleView addSubview:_searchBar];
    
    //Set to titleView
//    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = _searchBar;
    
    [self loadSearchHistory];
    [self createUI];
    
    isEmpty=YES;

}


#pragma mark --UITableViewDataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isEmpty==NO) {
        
//        JZJLog(@" _searchArray.count%zd",_searchArray.count);
        
        return _searchArray.count;
        
    }else
    {
    
//        JZJLog(@"dataArray count%zd",self.dataArray.count);

        if ([self.dataArray count]>0) {
            return self.dataArray.count + 1;
        }else{
            
            _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
            return 0;
        }

    
    }
    
 
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    

    
    if (isEmpty==NO) {
        
        
//        JZJLog(@"NavisearchCell");
        NavisearchCell* cell=[tableView dequeueReusableCellWithIdentifier:@"NavisearchCell"];

        if (!cell) {
            
            cell=[[NSBundle mainBundle]loadNibNamed:@"NavisearchCell" owner:nil options:nil][0];
            
            
            
        }
        
        
        Model * model=_searchArray[indexPath.row];
        

        [cell refreshWithModel:model WithIndexPath:indexPath];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        return cell;
        
    }else {
    
        JZJLog(@"UITableViewCell");

        UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"ID"];

        
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
            
            
            
            //tableview去掉多余线 cell
            _tableView.tableFooterView = [[UIView alloc]init];

        }
        
        if ((!_dataArray.count)==0) {
            if (indexPath.row==_dataArray.count) {
                cell.textLabel.text = @"清除历史";
                
                cell.textLabel.textAlignment=NSTextAlignmentCenter;
                cell.textLabel.center=cell.contentView.center;
                cell.textLabel.textColor=JZJYELLOW;
                
            }else{
//                JZJLog(@"row:%d",indexPath.row);
                cell.textLabel.text = _dataArray[indexPath.row];
            }
            
            return cell;

        }
    }
    
    
    
    
//    JZJLog(@"return nil");
        return nil;
    
    
    

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{


    if (isEmpty==NO) {
        
        
        return 100;
        
        
        
    }else{
    
    
    
        return 44;
    }

    
    
    
    return 0;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    
    if (isEmpty==YES) {
        
    
    if (indexPath.row==_dataArray.count) {
        [userDefaults removeObjectForKey:KEY];
        [userDefaults synchronize];
        [self loadSearchHistory];
    
        
        [tableView reloadData];
    }
    
    
    
    NSArray* historyArray= [userDefaults valueForKey:KEY];
    
    
    NSString* historyStr=historyArray[indexPath.row];
    
    
    
    
    [_searchBar setText:historyStr];
    
    [self searchBar:_searchBar textDidChange:historyStr];
    }
    
    else
    {
        JZJLog(@"%@",_searchArray);
    
        Model* model=_searchArray[indexPath.row];
    
        ThirdNaviSearchController* vc=[[ThirdNaviSearchController alloc]init];
        
        
        vc.model=model;

        [self.navigationController pushViewController:vc animated:YES];
        
        

        
    }
    
    
    
    
}

- (void)createUI

{

    self.automaticallyAdjustsScrollViewInsets=NO;


    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    
    _tableView.delegate=self;
    _tableView.dataSource=self;
    
    [self.view addSubview:_tableView];



}

- (void)loadSearchHistory{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *searchHistory = [userDefaults objectForKey:KEY];
    _dataArray = [[NSArray alloc] initWithArray:searchHistory];
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{

    
    
    
        NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
        
        NSArray *tempArray = [userDefault objectForKey:KEY];
        NSMutableArray *historyArray = nil;
        
        if (tempArray==nil) {
            historyArray=[NSMutableArray array];
        }else{
            historyArray = [NSMutableArray arrayWithArray:tempArray];
            
        }
        
        [historyArray addObject:searchBar.text];
        
        [userDefault setObject:historyArray forKey:KEY];
        
        [userDefault synchronize];
        

    
     ThridSearchController* vc=[[ThridSearchController alloc]init];
   
     vc.searchText=searchBar.text;
   
    vc.searchArray=self.searchArray;
    
    
    
    [self.navigationController pushViewController:vc animated:NO];
    
    
    

        


}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if (_searchArray==nil) {
        self.searchArray = [[NSMutableArray alloc] init];
    }else{
        [self.searchArray removeAllObjects];
    }
    
    
    
    if ([searchBar.text isEqualToString:@""] || searchBar.text==nil) {
        isEmpty = YES;
        [_tableView reloadData];
        
        
        return;
    }

   
    [DownLoad getFinderNavigationBarDataSearchWithUrl:[searchText URLEncode] andBlock:^(id obj, NSError * error) {

        
//        JZJLog(@"xx");
         NSArray* tempArray=  obj[@"data"][@"topics"];
        
        if (tempArray.count==0) {
            
//            JZJLog(@"空结果");

            
            isEmpty=YES;
            
            [_tableView reloadData];
            
        }else{
        
        [tempArray enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
            
            Model* model=[[Model alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [_searchArray addObject:model];
        
            
        }];
            
            isEmpty=NO;
            [_tableView reloadData];

        
        
        }
        
        
        
        
        
    }];
    
   
  
   
}




- (void)pop {
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}



@end
